import React, { Component } from 'react'
import { Card, Breadcrumb } from 'antd'
import { NavLink } from 'react-router-dom'
import {
  Button,
  Form,
  Input,
  Space,
  Table,
  Image,
  Switch,
  Modal,
  message
} from 'antd'
import type { FormInstance } from 'antd'
import type { User } from '@/types/user'
import { getUserList, addUser, updateUser, delUser } from '@/api/user'
import type { ColumnsType } from 'antd/es/table'
import { ExclamationCircleFilled } from '@ant-design/icons'

const { confirm } = Modal

const items = [
  {
    title: <NavLink to='/'>首页</NavLink>
  },
  {
    title: '用户管理'
  },
  {
    title: '用户列表'
  }
]

export default class MyUser extends Component {
  state = {
    page: 1,
    pageSize: 2,
    nickname: '', // 昵称
    total: 0,
    userList: [] as User[],
    isModalOpen: false, // 是否显示模态框
    mode: 'add',
    isChecked: true
  }

  // 为了获取Form表单实例
  formRef = React.createRef<FormInstance>()
  formRef2 = React.createRef<FormInstance>()

  getUserListData = async () => {
    const res = await getUserList({
      page: this.state.page,
      pageSize: this.state.pageSize,
      nickname: this.state.nickname
    })

    this.setState({
      userList: res.data.items,
      total: res.data.total
    })
  }

  search = () => {
    const result = this.formRef.current?.getFieldValue('nickname')
    this.state.nickname = result
    this.getUserListData()
  }

  componentDidMount (): void {
    this.getUserListData()
  }

  // Table中每一列长什么样子
  columns: ColumnsType<User> = [
    {
      title: '用户名',
      dataIndex: 'adminname'
    },
    {
      title: '用户昵称',
      dataIndex: 'nickname'
    },
    {
      title: '用户头像',
      dataIndex: 'avatar',
      render: avatar => {
        return <Image style={{ width: 50, height: 50 }} src={avatar} />
      }
    },
    {
      title: '状态',
      render: (_, { status }) => {
        return <Switch checked={status === 1} />
      }
    },
    {
      title: '操作',
      render: (_, record) => {
        return (
          <Space>
            <Button type='primary' onClick={() => this.edit(record)}>
              修改
            </Button>
            <Button
              type='primary'
              danger
              onClick={() => this.del(record.adminid)}
            >
              删除
            </Button>
          </Space>
        )
      }
    }
  ]

  // 用户的id
  adminid = ''

  // 修改用户
  edit = (user: User) => {
    // 把id存起来
    this.adminid = user.adminid

    this.setState(
      {
        mode: 'edit',
        isModalOpen: true,
        isChecked: user.status === 1 ? true : false
      },
      () => {
        // 给表单赋值
        this.formRef2.current?.setFieldsValue({
          adminname: user.adminname,
          nickname: user.nickname
        })
      }
    )
  }

  handleOk = async () => {
    try {
      // 校验表单中所有必填项，然后如果校验成功过，得到校验之后的结果，如果校验失败则抛出异常
      const results = await this.formRef2.current?.validateFields()

      results.status = results.status ? 1 : 0
      if (this.state.mode === 'add') {
        await addUser(results)
      } else {
        results.adminid = this.adminid
        await updateUser(results)
      }

      // 提示
      message.success(this.state.mode === 'add' ? '新增成功~' : '修改成功~')

      // 关闭弹框
      this.setState({
        isModalOpen: false
      })

      // 重新发请求，获取列表数据
      this.getUserListData()
    } catch (error) {
      console.log('---error---', error)
    }
  }

  // 取消
  cancel = () => {
    this.adminid = ''
    this.setState({ isModalOpen: false, isChecked: true, mode: 'add' }, () => {
      // 清空内容和清空校验
      this.formRef2.current?.resetFields()
    })
  }

  // 删除用户
  del = (adminid: string) => {
    confirm({
      title: '提示',
      icon: <ExclamationCircleFilled />,
      content: '确定删除该条数据吗',
      onOk: async () => {
        await delUser({ adminid })
        this.setState(
          {
            page: 1
          },
          () => {
            this.getUserListData()
          }
        )
      },
      onCancel () {
        console.log('Cancel')
      }
    })
  }

  render () {
    return (
      <div>
        <Card>
          <Breadcrumb items={items} />
          <Form
            layout='inline'
            ref={this.formRef}
            style={{ marginTop: 20 }}
            size='large'
          >
            {/* <Form.Item label='昵称' name='nickname'>
              <Input
                placeholder='请输入昵称进行搜索'
                style={{ width: 300 }}
                value={this.state.nickname}
                onChange={e => this.setState({ nickname: e.target.value })}
              />
            </Form.Item>
            <Form.Item>
              <Space>
                {' '}
                <Button type='primary' onClick={this.getUserListData}>
                  搜索
                </Button>
                <Button type='default'>+新增用户</Button>
              </Space>
              
            </Form.Item> */}
            <Form.Item label='昵称' name='nickname'>
              <Input placeholder='请输入昵称进行搜索' style={{ width: 300 }} />
            </Form.Item>
            <Form.Item>
              <Space>
                {' '}
                <Button type='primary' onClick={this.search}>
                  搜索
                </Button>
                <Button
                  type='default'
                  onClick={() => this.setState({ isModalOpen: true })}
                >
                  +新增用户
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Card>
        <Card style={{ marginTop: 10 }}>
          <Table
            dataSource={this.state.userList}
            columns={this.columns}
            rowKey='adminid'
            pagination={{
              position: ['bottomCenter'],
              total: this.state.total,
              showSizeChanger: true,
              showQuickJumper: true,
              pageSizeOptions: [1, 2, 5, 10],
              showTotal: () => `共 ${this.state.total} 条`,
              current: this.state.page,
              pageSize: this.state.pageSize,
              onChange: (page, pageSize) => {
                // this.setState是异步的
                this.setState(
                  {
                    page,
                    pageSize
                  },
                  () => {
                    this.getUserListData()
                  }
                )
              }
            }}
          />
        </Card>

        {/* 新增&修改的模块框 */}
        <Modal
          title={this.state.mode === 'add' ? '新增用户' : '修改用户'}
          open={this.state.isModalOpen}
          onOk={this.handleOk}
          onCancel={this.cancel}
        >
          <Form
            ref={this.formRef2}
            style={{ maxWidth: 600 }}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
            size='large'
          >
            <Form.Item
              label='用户名'
              name='adminname'
              rules={[{ required: true, message: '请输入用户名' }]}
            >
              <Input disabled={this.state.mode === 'edit'} />
            </Form.Item>

            <Form.Item
              label='用户昵称'
              name='nickname'
              rules={[{ required: true, message: '请输入用户昵称' }]}
            >
              <Input />
            </Form.Item>

            <Form.Item label='状态' name='status'>
              <Switch
                checked={this.state.isChecked}
                onChange={(checked: boolean) =>
                  this.setState({
                    isChecked: checked
                  })
                }
              />
            </Form.Item>
          </Form>
        </Modal>
      </div>
    )
  }
}
